<template>
    <div class="jianzhan-content">
        <Crumb name="Close Order"/>
        <div class="content">
            <Search>
                <el-input
                        v-model="key"
                        size="small"
                        class="input"
                        placeholder="Search By Request No"
                        prefix-icon="el-icon-search"/>
            </Search>
            <div class="table-wrapper">
                <el-table
                        :data="closeList.slice((pageNum-1) * pageSize,pageNum * pageSize)"
                        border
                        row-key="id"
                        stripe
                        style="width: 100%"
                >
                    <el-table-column type="expand" label="problem" width="80">
                        <template slot-scope="quest">
                            <div v-for="item in quest.row.problemVoList" :key="item.id">
                                <span>{{item.problemDescription}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="requestName"
                            label="Request Number"
                    />
                    <el-table-column
                            prop="workingNo"
                            label="Working Number"
                    />
                    <el-table-column
                            prop="requestDate"
                            label="Request Date"
                    />
                    <el-table-column
                            prop="requestBy"
                            label="Request By"
                    />
                    <el-table-column
                            prop="plateNum"
                            label="PlateNum"
                    />
                    <el-table-column
                            prop="serviceType"
                            label="Service Type"
                    />
                    <el-table-column>
                        <template slot-scope="request">
                            <el-button size="small" @click="showDetail(request.row)">Close Order</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"></el-pagination>
                </div>
            </div>
        </div>

        <el-dialog title="Close Order" :visible.sync="dialogVisible" width="100%" top="0">
            <quest-show :quest="quest"/>
            <div class="spin"></div>
            <work-order-show :work="work"/>
            <div class="spin"></div>
            <el-form label-width="150px">
                <div style="display: flex">
                    <div class="flex-content">
                        <el-form-item label="Actual Problem">
                            <div class="problem" v-for="(item,index) in close.problemVoList" :key="index"
                                 style="position: relative;margin-bottom: 10px;">
                                <el-input v-model="item.problemDescription" type="textarea" size="small"
                                          class="my-input"/>
                                <el-button @click="showProblem(item,index)" type="warning"
                                           style="width: 20px;height: 20px;padding: 0;vertical-align: middle;margin-left: 10px;margin-bottom: 12px;">
                                    <i class="el-icon-document"/>
                                </el-button>
                            </div>
                            <el-button @click="addProblem" type="primary"
                                       style="width: 20px;height: 20px;padding: 0;vertical-align: top;position: absolute;top: 15px;right: 10px;">
                                <i class="el-icon-plus"/>
                            </el-button>
                        </el-form-item>

                        <el-form-item label="Cause Of problem">
                            <el-input v-model="close.causeOfProblem" size="small" class="my-input" placeholder="Cause of problem"></el-input>
                        </el-form-item>

                        <el-form-item label="Action ">
                            <div class="problem" v-for="(item,index) in close.suggestionVoList" :key="index"
                                 style="position: relative;margin-bottom: 10px;">
                                <el-input v-model="item.problemDescription" type="textarea" size="small"
                                          class="my-input"/>
                                <el-button @click="showAction(item,index)" type="warning"
                                           style="width: 20px;height: 20px;padding: 0;vertical-align: middle;margin-left: 10px;margin-bottom: 12px;">
                                    <i class="el-icon-document"/>
                                </el-button>
                            </div>
                            <el-button @click="addAction" type="primary"
                                       style="width: 20px;height: 20px;padding: 0;vertical-align: top;position: absolute;top: 15px;right: 10px;">
                                <i class="el-icon-plus"/>
                            </el-button>
                        </el-form-item>
                    </div>
                    <div class="flex-content">
                        <el-form-item label="Remarks">
                            <el-input type="textarea" v-model="close.remarks" size="small" class="my-input"/>
                        </el-form-item>
                        <el-form-item label="Unit">
                            <el-select v-model="close.unit" size="small" class="my-input">
                                <el-option
                                        v-for="item in unitList"
                                        :key="item"
                                        :label="item"
                                        :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="Category">
                            <el-select v-model="close.category" size="small" class="my-input">
                                <el-option
                                        v-for="item in cateList"
                                        :key="item"
                                        :label="item"
                                        :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="point code">
                            <el-select v-model="close.pointCode" placeholder="point code" size="small" class="my-input">
                                <el-option
                                        v-for="item in workCodeList"
                                        :key="item.pointCode"
                                        :value="item.pointCode"
                                        :label="item.description+'/'+item.hours">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="flex-content">
                        <el-form-item label="End Date">
                            <el-date-picker size="small" v-model="close.endDate" value-format="yyyy-MM-dd HH:mm:ss"
                                            type="datetime"/>
                        </el-form-item>
                        <el-form-item label="Hand over">
                            <el-select v-model="close.handOver" placeholder="Hand over" size="small">
                                <el-option
                                        v-for="item in employeeList"
                                        :key="item.id"
                                        :label="item.employeeName"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
            <div class="spin"></div>
            <!--<el-button type="primary" size="small" style="margin-top: 20px;margin-bottom: 20px;float: left;"-->
                       <!--@click="dbVisible = true">Add parts <i class="el-icon-plus"/></el-button>-->
            <spDataBase @deleteItem="deleteItem" :edit="false" :partList="partList"/>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                        <el-button type="primary" @click="submitForm">Confirm</el-button>
                    </span>
        </el-dialog>

        <Part-item @close="dbVisible = false" @add="add" :visible="dbVisible"/>
        <problem :visible="fileShow1" :picture="picture" :video="video" :file="file" @close="close1" @sub="sub1"/>
        <problem :visible="fileShow2" :picture="picture" :video="video" :file="file" @close="close2" @sub="sub2"/>
    </div>
</template>

<script>
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import spDataBase from '@/components/part/spDataBase'
    import PartItem from '@/components/part/sparePartItem'
    import questShow from '@/components/service/questShow'
    import problem from '@/components/service/problem'
    import {
        getCloseList,
        showQuestDetail,
        getWorkDetail,
        getRealParts,
        closeOrder,
        getCloseUnit,
        getCloseCategory,
        getCloseWorkCode,
        getEmployeeList
    } from "../../api/service";
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import dbMixins from '../../util/spMixins'
    import WorkOrderShow from "../../components/service/workOrderShow";

    const quest = {
        requestNo: '',
        requestDate: '',
        initiator: '',
        customerId: '',
        customerName: '',
        addressId: '',
        address: '',
        distance: '',
        unitModel: '',
        sn: '',
        deliveryTime: '',
        hmKm: '',
        typeCode: '',
        serviceType: "",
        appointmentTime: '',
        note: '',
        status: "",
        projectName: '',
        plateNum: '',
        charges: [],
        reason: '',
        problems: [{
            problemDescription: '',
            problemPhoto: [],
            problemVideo: [],
            problemFile: []
        }],
        id: '',
    };
    export default {
        name: "close-order",
        mixins: [mixins, dbMixins],
        data() {
            return {
                key: '',
                close: {
                    unit: '',
                    category: '',
                    pointCode: '',
                    handOver: '',
                    causeOfProblem:'',
                    recommendationList: [{sn: '', description: ''}],
                    endDate: '',
                    problemVoList: [{
                        problemDescription: '',
                        problemPhoto: [],
                        problemVideo: [],
                        problemFile: []
                    }],
                    suggestionVoList: [{suggestion: '', problemPhoto: [], problemVideo: [], problemFile: []}],
                    remarks: ''

                },
                quest: {...quest},
                work: {
                    workingNo: '',
                    woStatus: 2,
                    arrangedBy: '',
                    suratJalanNo: '',
                    salesOrderNo: '',
                    workingPlace: '',
                    continueWoReason: '',
                    continueWoDate: '',
                    continueWoNo: '',
                    date: '',
                    jobReceiver: [{receiverId: ''}]
                },
                list: [],
                unitList: [],
                cateList: [],
                workCodeList: [],
                employeeList: [],
                dialogVisible: false,
                woStatus: [{key: 0, value: 'On Progress'}, {key: 1, value: 'Wait for spareparts'}, {
                    key: 2,
                    value: 'Reschedule'
                }, {key: 3, value: 'Finished'}, {key: 4, value: 'Job Continue'}],
                fileShow1: false,
                fileShow2: false,
                picture: [],
                video: [],
                file: []
            }
        },
        computed: {
            closeList() {
                return this.list.filter(item => item.requestNo.indexOf(this.key) > -1)
            }
        },
        created() {
            this._getCloseList();
            this._getEmployeeList();
            this.getUnit();
            this.getCategory();
        },
        methods: {
            async _getEmployeeList() {
                const {status, data} = await getEmployeeList();
                if (status === ERROR_OK) {
                    this.employeeList = data
                }
            },
            async getUnit() {
                const {status, data} = await getCloseUnit();
                if (status === ERROR_OK) {
                    this.unitList = data;
                }
            },
            async getCategory() {
                const {status, data} = await getCloseCategory();
                if (status === ERROR_OK) {
                    this.cateList = data
                }
            },
            async getPointCode(unit,category){
                const {status,data} = await getCloseWorkCode({unit,category});
                if(status === ERROR_OK) {
                    this.workCodeList = data
                }
            },
            async submitForm() {
                let problem = this.close.problemVoList;
                const newProblem = [];
                problem.forEach(item => {
                    newProblem.push({
                        problemDescription: item.problemDescription,
                        problemPhoto: item.problemPhoto ? item.problemPhoto.join(',') : '',
                        problemFile: item.problemFile ? item.problemFile.join(',') : '',
                        problemVideo: item.problemVideo ? item.problemVideo.join(',') : ''
                    })
                });
                const recommendation = JSON.stringify(this.close.recommendation);
                let suggestion = this.close.suggestionVoList;
                const newSuggestion = [];
                suggestion.forEach(item => {
                    newSuggestion.push({
                        suggestion: item.suggestion,
                        photo: item.problemPhoto ? item.problemPhoto.join(',') : '',
                        video: item.problemVideo ? item.problemVideo.join(',') : '',
                        file: item.problemFile ? item.problemFile.join(',') : ''
                    })
                });
                let sparePartsList = this.partList.map(part => {
                    return {
                        partsId: part.id,
                        partsQuantity: part.number,
                        workOrderNum: this.work.workingNo
                    }
                });
                const {orderId} = this.work;
                const {remarks, endDate,handOver,unit,category,causeOfProblem,pointCode} = this.close;
                sparePartsList = JSON.stringify(sparePartsList);
                const {status} = await closeOrder({
                    orderId,
                    remarks,
                    endDate,
                    recommendation,
                    problem: JSON.stringify(newProblem),
                    suggestion: JSON.stringify(newSuggestion),
                    depletes: sparePartsList,
                    handOver,unit,category,causeOfProblem,pointCode
                });
                if (status === ERROR_OK) {
                    this.$message.success('Success');
                    this.dialogVisible = false;
                    this._getCloseList();
                    this.clear();
                }
            },
            async _getCloseList() {
                const {status, data} = await getCloseList();
                if (status === ERROR_OK) {
                    this.list = data.list;
                    this.total = data.list.length
                }
            },
            async _getDetail(id) {
                const {status, data} = await showQuestDetail(id);
                if (status === ERROR_OK) {
                    this.quest = data.orderVo;
                    if (data.problemVoList.length) {
                        this.$set(this.quest, 'problems', data.problemVoList);
                    } else {
                        this.$set(this.quest, 'problems', [{
                            problemDescription: '',
                            problemPhoto: [],
                            problemVideo: [],
                            problemFile: []
                        }])
                    }
                    this.quest.problems = data.problemVoList

                }
            },
            async _getRealPart(workOrderNo) {
                const {status, data} = await getRealParts(workOrderNo);
                if (status === ERROR_OK) {
                    this.partList = data.map(part => {
                        return {
                            ...part.spareParts,
                            number: part.partsQuantity
                        }
                    })
                } else {
                    this.partList = []
                }
            },
            async _getWorkDetail(id) {
                const {status, data} = await getWorkDetail(id);
                if (status === ERROR_OK) {
                    this.work = data;
                    this.$set(this.work, 'jobReceiver', data.jobReceiverVoList)
                }
            },
            close1() {
                this.fileShow1 = false
            },
            close2() {
                this.fileShow2 = false
            },
            sub1(file) {
                const current = {...this.current, ...file};
                this.close.problemVoList.splice(this.index, 1, current);
                this.close1();
            },
            sub2(file) {
                const current = {...this.current, ...file};
                this.close.suggestionVoList.splice(this.index, 1, current);
                this.close2();
            },
            showProblem(item, index) {
                this.picture = item.problemPhoto;
                this.video = item.problemVideo;
                this.file = item.problemFile;
                this.current = item;
                this.index = index;
                this.fileShow1 = true
            },
            showAction(item, index) {
                this.picture = item.problemPhoto;
                this.video = item.problemVideo;
                this.file = item.problemFile;
                this.current = item;
                this.index = index;
                this.fileShow2 = true
            },
            addProblem() {
                this.close.problemVoList.push({
                    problemDescription: '',
                    problemPhoto: [],
                    problemVideo: [],
                    problemFile: []
                })
            },
            addAction() {
                this.close.suggestionVoList.push({photo: [], video: [], file: [], suggestion: ''})
            },
            addRec() {
                this.close.recommendationList.push({sn: '', description: ''})
            },
            clear() {
                this.close = {
                    recommendationList: [{sn: '', description: ''}],
                    endDate: '',
                    problemVoList: [{
                        problemDescription: '',
                        problemPhoto: [],
                        problemVideo: [],
                        problemFile: []
                    }],
                    suggestionVoList: [{suggestion: '', problemPhoto: [], problemVideo: [], problemFile: []}],
                    remarks: '',
                    handOver:'',
                    unit:'',
                    category:'',
                    causeOfProblem:'',
                    pointCode:''

                }
            },
            showDetail(work) {
                this._getDetail(work.id);
                this._getWorkDetail(work.workingId);
                this._getRealPart(work.workingNo);
                this.dialogVisible = true;
            },
        },
        components: {
            WorkOrderShow,
            Crumb, Search, spDataBase, PartItem, questShow, problem
        },
        watch: {
            workList(list) {
                this.total = list.length
            },
            'close.category':{
                handler:function(category){
                    if(this.close.unit && category) {
                        this.getPointCode(this.close.unit,category);
                        this.close.pointCode = ''
                    }
                },
                deep:true
            }
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    .spin {
        border-bottom: 2px dashed #ddd;
        width: 100%;
        height: 0;
        margin-top: 20px;
    }
</style>